<template>
  <view>
    <button @click="showMap = true">选择位置</button>
    <map
      v-if="showMap"
      id="myMap"
      :latitude="mapCenter.latitude"
      :longitude="mapCenter.longitude"
      --
      @tap="handleMapTap"
    >
      >
    </map>
  </view>
</template>

<script setup>
import { ref } from "vue";

const showMap = ref(false);
const location = ref(null);
const mapCenter = ref({ latitude: 39.9042, longitude: 116.4074 }); // 默认北京

const handleMapTap = (e) => {
  const { latitude, longitude } = e.detail;
  // 逆地理编码获取地址名称
  uni.request({
    url: `https://restapi.amap.com/v3/geocode/regeo?key=215af0c59d107e56c394d45fe1ba4d04&location=${longitude},${latitude}`,
    success: (res) => {
      const address = res.data.regeocode.formatted_address;
      location.value = {
        name: address.split(" ")[0] || "未知位置",
        address: address,
        latitude: latitude,
        longitude: longitude,
      };
      showMap.value = false;
    },
  });
};
</script>
